package com.alibaba.yinan.domain.task.config;

import com.alibaba.yinan.domain.task.enums.TaskEvent;
import com.alibaba.yinan.domain.task.enums.TaskStatus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.config.StateMachineBuilder;

import java.util.EnumSet;

/**
 * @ClassName TaskStateMachineConfig
 * @Author mengke
 * @create 2025/8/3 21:00
 * @Description
 */
@Configuration
public class TaskStateMachineConfig {

    @Bean
    public StateMachine<TaskStatus, TaskEvent> taskStateMachine() throws Exception {
        StateMachineBuilder.Builder<TaskStatus, TaskEvent> builder = StateMachineBuilder.builder();

        builder.configureStates()
                .withStates()
                .initial(TaskStatus.CREATED)
                .states(EnumSet.allOf(TaskStatus.class));

        builder.configureTransitions()
                .withExternal().source(TaskStatus.CREATED).target(TaskStatus.DISPATCHED).event(TaskEvent.DISPATCH).and()
                .withExternal().source(TaskStatus.DISPATCHED).target(TaskStatus.RUNNING).event(TaskEvent.START).and()
                .withExternal().source(TaskStatus.RUNNING).target(TaskStatus.COMPLETED).event(TaskEvent.COMPLETE).and()
                .withExternal().source(TaskStatus.RUNNING).target(TaskStatus.FAILED).event(TaskEvent.FAIL).and()
                .withExternal().source(TaskStatus.RUNNING).target(TaskStatus.SUSPENDED).event(TaskEvent.SUSPEND).and()
                .withExternal().source(TaskStatus.SUSPENDED).target(TaskStatus.RUNNING).event(TaskEvent.RESUME);

        return builder.build();
    }
}
